using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace AssemblyCYG
{
    public class CINIFactory
    {
        string iniFilePath = string.Empty;

        #region API函数声明

        [DllImport("kernel32")]//返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);

        #endregion

        #region 读Ini文件

        public CINIFactory(string path,string settingName)
        {
            FileStream stream = null;
            this.iniFilePath = string.Format(@"{0}{1}.ini", path, settingName);
            if (Directory.Exists(path))
            {
                if (!File.Exists(iniFilePath))
                {
                    //创建Log文件
                    stream = File.Create(iniFilePath);
                }
                else
                {
                }
            }
            else
            {
                //创建根Log文件夹
                Directory.CreateDirectory(path);
                //创建Log文件
                stream = File.Create(iniFilePath);
            }

            if (stream != null)
                stream.Dispose();
        }

        public string ReadIniData(string Section, string Key, string NoText)
        {
            StringBuilder temp = new StringBuilder(1024);
            GetPrivateProfileString(Section, Key, NoText, temp, 1024, this.iniFilePath);
            return temp.ToString();
        }

        #endregion

        #region 写Ini文件

        public bool WriteIniData(string Section, string Key, string Value)
        {
            long OpStation = WritePrivateProfileString(Section, Key, Value, this.iniFilePath);
            if (OpStation == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion
    }
}
